/**
* Define Enhancements
*/
$.enhance(HQ.components.tabsCollapse, {title: "Tabs Tablet/Desktop and Collapse in mobile device", id: "tabs-collapse"});
$.enhance(HQ.components.tabs, {title: "Tabs", id: "tabs"});
$.enhance(HQ.components.collapse, {title: "Collapse", id: "collapse"});
$.enhance(HQ.components.moveTo, {title: "Move element to a destination (desktop/mobile)", id: "move-to"});
$.enhance(HQ.components.formSelectPanel, {title: "Form select tag open specific panel", id: "form-select-panel"});
/**
* Document Ready / Apply Enhance
*/
$(document).ready(function () {
// Init Enhance
$(this).enhance();
var lang = $('html').attr('lang'),
langShort = lang === 'fr' ? 'F' : 'A';
// langShort = lang.charAt(0).toUpperCase();
/* Residential */
var RES_container = lang === 'fr' ? '#residentielPanel' : '#residentialPanel', // Container where pannels are appended
RES_select = '#ClientResSelect', // Select input responsible for panels
RES_source = $('#ResPanelTemplate').html(), // Template source for the pannels
RES_template = Handlebars.compile(RES_source); // Compiled template by Handlebars
/* Business */
var COMM_container = lang === 'fr' ? '#affairesPanel' : '#businessPanel', // Container where pannels are appended
COMM_select = '#ClientAffSelect', // Select input responsible for panels
COMM_source = $('#AffPanelTemplate').html(), // Template source for the pannels
COMM_template = Handlebars.compile(COMM_source); // Compiled template by Handlebars
/* Is holiday */
var isHolidayDay = false;
if (typeof holidayDate != 'undefined') {
if (!jQuery.isEmptyObject(holidayDate)) {
var holidayRange = moment().range(moment(holidayDate.from), moment(holidayDate.to));
var dateToday = moment().format('YYYY-MM-DD');
if(holidayRange.contains(moment(dateToday)) ) {
isHolidayDay = true;
}
}
}
//Init handler check change in Sujet select
initEventSujetRes();
checkWaitTimeAll('#ClientResSelect');
/* Data vars */
var delayData, tableData, closedDates;
$.when(
$.getJSON('/themes/racine/data/donnees-nous-joindre/FichierTempsAttenteRVI.json', function(data) {
delayData = data;
}),
$.getJSON('/themes/nous-joindre/data/TableCorrespondance.json?v=' + new Date().getTime(), function(data) {
tableData = data.filesAttente;
}),
$.getJSON('/themes/nous-joindre/data/DateFermeture.json?v=' + new Date().getTime(), function(data) {
closedDates = data.datesFermeture;
})
).then(function() {
if(tableData) {
var RES_dd = [],
COMM_dd = [],
count = tableData.length;
$(RES_select).clearEnhance();
$(COMM_select).clearEnhance();
$('#toEnhence').clearEnhance();
// Process data
$.each(tableData, function(i, subject) {
// DATA DELAY
if(delayData && subject.nomFile != '') {
subject.fileAttente = lookup(delayData, 'Groupe_File', subject.nomFile);
var timestamp = moment(subject.fileAttente.Date_Creation).format('H:mm');
subject.lastUpdate = lang === "fr" ? timestamp.replace(':', ' h ') : timestamp;
}else {
// Request for delayData didn't work, handle it
// subject.fileAttente = delayData[subject.nomFile];
}
// DATA RES
if(subject.langue === langShort && subject.segmentation === 'RES') {
var html = RES_template(subject);
$(RES_container).find('.pnl-insert-after').after(html);
RES_dd.push('');
}
// DATA AFF
if(subject.langue === langShort && subject.segmentation === 'COMM') {
var html = COMM_template(subject);
$(COMM_container).find('.pnl-insert-after').after(html);
// $('.hq-collapse').trigger('ready');
COMM_dd.push('');
}
// Re-Init enhence
if(!--count) {
$('#toEnhence').enhance();
/* Residential */
$(RES_select).enhance(); // Dropdown menu
$(RES_container).find('.my-collapse').each(function() {
$(this).enhance(); // Collapse
});
$(RES_select).val($(RES_select + ' option:first').val());
$(RES_container).find('.js-info-box-selected').each(function() {
$(this).enhance(); // Info box (grey box)
});
/* Business */
$(COMM_select).enhance(); // Dropdown menu
$(COMM_container).find('.my-collapse').each(function() {
$(this).enhance(); // Collapse
});
$(COMM_select).val($(COMM_select + ' option:first').val());
$(COMM_container).find('.js-info-box-selected').each(function() {
$(this).enhance(); // Info box (grey box)
});
}
});
// Populate dropdowns
$(RES_select).append(RES_dd.join(''));
$(COMM_select).append(COMM_dd.join(''));
if ($(RES_select).hasClass('selectFirst')) {
$(RES_select).change();
}
if ($(COMM_select).hasClass('selectFirst')) {
$(COMM_select).change();
}
// Handling parameters for dropdow menu and RV collapse
var subjectParam = getParameterByName('subj');
var rvParam = getParameterByName('rv');
if(subjectParam && subjectParam != '') {
var activePanel = $('.tab-pane.active'), // Current panel (Residentiel, Business)
panelSelect = activePanel.find('select'),
panelPrefix = activePanel.attr('id').toLowerCase().charAt(0), // Prefix to use for option value
panelPrefix = panelPrefix == 'b' ? 'a' : panelPrefix, // If prefix is "b" (for business), switch to "a" (for affaires)
subjectRefID = 'pnl-c' + panelPrefix + '-' + subjectParam; // Constructed option value to use for select
if(panelSelect.find('option[value=' + subjectRefID + ']').length) {
// Set subject based on id provided with parameter "s"
panelSelect.val(subjectRefID).change();
if(rvParam && rvParam != '') {
var rvCollapseTrigger = activePanel.find('.' + subjectRefID + ' .panel-rv').children('a');
rvCollapseTrigger.click();
$('html, body').animate({
scrollTop: activePanel.offset().top - 80
}, 500);
}
}
}
// prevent double call in nous-joindre page
if($("#hq-nous-joindre-n1").length === 0) {
// Trigger a ready event after templates are done compiling
$('.hq-collapse').trigger('ready');
}
//timeSelectedSubject();
}else {
// Request for tableData didn't work, handle it
}
/*
* STAGING QA : Customer space link rewrite
*/
var origin = window.location.origin,
stagingOrigin = 'http://www-staging-qa.hydro.qc.ca', //doit être http parce que sur dpcomm
prodOrigin = 'https://www.hydroquebec.com'; //doit être http parce que sur dpcomm
// Only if we are on Staging QA
if(origin === stagingOrigin && origin != prodOrigin) {
var links = $('a[href*="https://www.hydroquebec.com/portail/"]');
$.each(links, function() {
var href = $(this).attr('href');
// Rewrite link from prod to staging
$(this).attr('href', href.replace('https://www.hydroquebec.com', 'https://was8aqzce01.hydro.qc.ca'));
});
}
});
// Handlebars helpers
Handlebars.registerHelper('tel', function(string) {
return string.toString().replace(/\s+/g, '').replace('-', '');
});
Handlebars.registerHelper('time', function(string) {
if(lang === "fr") {
moment.locale('fr-ca');
return moment(string, 'HH:mm').format('H:mm').replace(':', ' h ');
}else {
moment.locale('en');
return moment(string, 'HH:mm').format('LT').replace('AM', 'a.m.').replace('PM', 'p.m.').replace(':00', '');
// return moment(string, 'HH:mm').format('H:mm a');
}
});
Handlebars.registerHelper('ifHasParam', function(param, value, options) {
if(getParameterByName(param) === value) {
return options.fn(this);
}
return options.inverse(this);
});
Handlebars.registerHelper('hours', function(data, options) {
// Set timezone data
var tzObj = moment().tz('America/Toronto'),
tzTime = moment(tzObj.format('HH:mm'), 'HH:mm'),
tzDayOfWeek = tzObj.day();
// If weekend is closed and we are currently in weekend, return.
if(!data.heuresWeekend && (tzDayOfWeek == 6 || tzDayOfWeek == 0)) {
data.state = 'isclose';
data.isopen = false;
return options.fn(data);
}
//AJOUT 2021-02-16
// Close l'ouverture le dimanche pour résidentiel
if(data.heuresWeekend && (tzDayOfWeek == 0)) {
data.state = 'isclose';
data.isopen = false;
return options.fn(data);
}
// If weekend is closed and we are currently in weekend, return.
if(!data.heuresSemaine && (tzDayOfWeek == 1 || tzDayOfWeek == 2 || tzDayOfWeek == 3 || tzDayOfWeek == 4 || tzDayOfWeek == 5)) {
data.state = 'isclose';
data.isopen = false;
return options.fn(data);
}
// Set opening hours data
var hoursWeek = {
'open' : moment(data.heuresSemaine.ouverture, 'HH:mm'),
'close' : moment(data.heuresSemaine.fermeture, 'HH:mm')
};
var hoursWeekend = {
'open' : moment(data.heuresWeekend.ouverture, 'HH:mm'),
'close' : moment(data.heuresWeekend.fermeture, 'HH:mm')
};
var hoursOpenHolidays = {
'open' : moment(data.heuresFerieOuvert.ouverture, 'HH:mm'),
'close' : moment(data.heuresFerieOuvert.fermeture, 'HH:mm')
};
// Choose right set of data (week or weekend data)
var hours = (tzDayOfWeek == 6 || tzDayOfWeek == 0) ? hoursWeekend : hoursWeek;
//if it's holiday, holiday schedule overwrite usual schedule
if(isHolidayDay) {
hours = hoursOpenHolidays;
}
data.closeAt = hours.close;
var isClosedOnDates = false,
today = moment().format('YYYY-MM-DD');
// Check to see if today is between closed dates
// @SOURCE = /themes/nous-joindre/data/DateFermeture.json
$.each(closedDates, function() {
var startDate = moment(this.from),
endDate = moment(this.to),
range = moment().range(startDate, endDate),
date = moment(today);
// If today is between closed dates, set a flag to use in condition below
if(range.contains(date)) {
isClosedOnDates = true;
// If a message is specified, send it to template
var messages = lang === 'fr' ? this.messages_fr : this.messages_en;
if(messages) {
data.tooltipMessage = new Handlebars.SafeString(messages.tooltip);
}
}
});
if(!isClosedOnDates && tzTime.isAfter(hours.open) && tzTime.isBefore(hours.close) || tzTime.isSame(hours.open) || tzTime.isSame(hours.close)) {
data.state = 'isopen';
data.isopen = true;
}else {
data.state = 'isclose';
data.isopen = false;
}
return options.fn(data);
});
Handlebars.registerHelper('wait', function(data, options) {
var now = moment().tz('America/Toronto').format('YYYY-MM-DD HH:mm:ss'),
hasWaitTime = data.Delai_obtenu === 'Oui',
waitTime = parseInt(data.Delai_moyen_attente, 10),
waitMin = parseInt(data.Delai_minimum, 10),
waitMax = parseInt(data.Delai_maximum, 10),
timestamp = moment(data.Date_Creation).format('YYYY-MM-DD HH:mm:ss'),
ms = moment(now, 'YYYY-MM-DD HH:mm:ss').diff(moment(timestamp, 'YYYY-MM-DD HH:mm:ss')),
timeSinceUpdate = Math.round(moment.duration(ms).asMinutes()),
out = {};
timeSinceUpdate = 15;
if(data && hasWaitTime && timeSinceUpdate < 20) {
if(lang === 'fr') {
if(waitTime > waitMin && waitTime < waitMax || waitMin === 0 && waitTime > 0 && waitTime < waitMax || waitMax === 0 && waitTime > 0 && waitTime > waitMin) {
out.delay = 'Environ ' + waitTime + ' minutes d’attente.';
out.line1 = new Handlebars.SafeString('Pour éviter d’attendre, vous pouvez :');
out.line2 = new Handlebars.SafeString('prendre un rendez-vous téléphonique.');
}else if(waitTime < waitMin && waitTime > 0) {
out.delay = 'Moins de ' + waitMin + ' minutes d’attente.';
out.line1 = new Handlebars.SafeString('Pour éviter d’attendre, vous pouvez :');
out.line2 = new Handlebars.SafeString('prendre un rendez-vous téléphonique.');
}else if(waitTime > waitMax) {
out.delay = 'Plus de ' + waitMax + ' minutes d’attente.';
out.line1 = new Handlebars.SafeString('Pour éviter d’attendre, vous pouvez :');
out.line2 = new Handlebars.SafeString('prendre un rendez-vous téléphonique.');
}else {
out.delay = 'Moins de 2 minutes d’attente.';
out.line1 = new Handlebars.SafeString('Vous pouvez aussi');
out.line2 = new Handlebars.SafeString('prendre un rendez-vous téléphonique.');
}
}else {
if(waitTime > waitMin && waitTime < waitMax || waitMin === 0 && waitTime > 0 && waitTime < waitMax || waitMax === 0 && waitTime > 0 && waitTime > waitMin) {
out.delay = 'The wait time is approximately ' + waitTime + ' minutes';
out.line1 = new Handlebars.SafeString('If you don’t want to wait:');
out.line2 = new Handlebars.SafeString('Schedule a callback');
}else if(waitTime < waitMin && waitTime > 0) {
out.delay = 'The wait time is less than ' + waitMin + ' minutes.';
out.line1 = new Handlebars.SafeString('If you don’t want to wait:');
out.line2 = new Handlebars.SafeString('Schedule a callback');
}else if(waitTime > waitMax) {
out.delay = 'The wait time is over ' + waitMax + ' minutes.';
out.line1 = new Handlebars.SafeString('If you don’t want to wait:');
out.line2 = new Handlebars.SafeString('Schedule a callback');
}else {
out.delay = 'The wait time is less than 2 minutes.';
out.line1 = new Handlebars.SafeString('If you don’t want to wait:');
out.line2 = new Handlebars.SafeString('Schedule a callback');
}
}
}else {
console.log('NoWaitTime', hasWaitTime, timeSinceUpdate)
if(lang === 'fr') {
// out.line1 = new Handlebars.SafeString('Pour éviter d’attendre, vous pouvez');
// out.line2 = new Handlebars.SafeString('prendre un rendez-vous téléphonique.');
out.line2 = new Handlebars.SafeString('Vous pouvez prendre un rendez-vous téléphonique');
}else {
out.line2 = new Handlebars.SafeString('You may also schedule a callback');
}
hasWaitTime = false;
}
out.hasWaitTime = hasWaitTime;
return options.fn(out);
});
Handlebars.registerHelper('waitChat', function(data, options) {
out = {};
return options.fn(out);
});
});
// Parse array function
function lookup(arr, key, val) {
for(var i = 0, length = arr.length; i < length; i++) {
if (arr[i][key] === val) {
return arr[i]; // Return as soon as the object is found
}
}
return null; // The object was not found
};
// Get parameter function
// http://stackoverflow.com/q/901115
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
let arrayOfTime = new Array();
let activeOption;
function initEventSujetRes() {
const sujetRes = document.querySelector('#ClientResSelect');
sujetRes.addEventListener('change', function (e) {
checkWaitTimeAll('#ClientResSelect');
//var optionSujet = e.target.value;
//checkWaitTimeInRes(optionSujet);
});
}
/*function timeSelectedSubject() {
const sujetRes = document.querySelector('#ClientResSelect');
let selected = sujetRes.options[0].value;
//console.log(selected)
//checkWaitTimeInRes(selected);
}*/
/* POUR CLAVARDAGE seulement */
/* Temps pour un sujet */
function checkWaitTimeInRes(os) {
/// LOAD data selon le sujet
let oldValue = os;
let sujetMap = mappingSujet(os);
let langFile = (lang === 'fr') ? 'FR' : 'AN';
let sujetToFetch = sujetMap + '_' + langFile;
const baseUrl = "https://ccc-lx.hydroquebec.com/genesys/1/internal_statistic/urs/stat/sdata?stat=AverDistribCallTime&tenant=Environment&targets=";
const finalUrl = baseUrl + sujetToFetch + '.GRP';
if(sujetMap) {
$.getJSON( finalUrl, function( response ) {
let seconds = Object.keys(response).map(function(e) {
return response[e]
});
let time = secondsToMinutes(seconds);//get value form key // TIME is in seconds
arrayOfTime.push(time);
//updateWaitTimeChat(time, oldValue);
});
} else {
arrayOfTime.push(0);
}
/* if(sujetMap) {
fetch(finalUrl)
.then(response => response.json())
.then( function(json) {
let time = secondsToMinutes(Object.values(json))//get value form key // TIME is in seconds
arrayOfTime.push(time);
}
)
.catch( function(error) {
console.error(error);
});
} else {
arrayOfTime.push(0);
}*/
}
/* Temps le selon tous les sujets */
// 1. Extraire la valeur des options -> Array
// 2. Looper le array pour extraire les temps et les sauvegarder dans un array
// 3. Extraire du array la valeur (temps) la plus élevé
// 4. Afficher le temps sur la page
function checkWaitTimeAll() {
// HAck attends que les options du select soit rempli
setTimeout( function() {
listTime = extractOptions("#ClientResSelect");
//ES5
for (var i = 0; i < listTime.length; i++) {
if(listTime[i]) {
// console.log('sujet', listTime[i])
checkWaitTimeInRes(listTime[i]);
}
}
//ES6
/*for (os of listTime) {
//console.log('Sujet', os);
if(os) {
checkWaitTimeInRes(os);
}
}*/
setTimeout( function() {
let maxTime = Math.max.apply(null, arrayOfTime);
updateWaitTimeChat(maxTime, activeOption);
},250)
},500)
}
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
function extractOptions(el) {
//ES5
var arrayTime = new Array();
for (var i = 0; i < document.querySelector("#ClientResSelect").options.length; i++) {
var option_value = document.querySelector("#ClientResSelect").options[i].value;
arrayTime.push(option_value);
e = document.querySelector("#ClientResSelect");
activeOption = e.options[e.selectedIndex].value;
}
//ES6
/*
let arrayTime = Array();
Array.from(document.querySelector("#ClientResSelect").options).forEach(function(option_element) {
let option_value = option_element.value;
arrayTime.push( option_value );
e = document.querySelector("#ClientResSelect");
activeOption = e.options[e.selectedIndex].value;
});
console.log('ArrayTime', arrayTime);
return arrayTime;
*/
// console.log('ArrayTime', arrayTime);
return arrayTime;
}
function mappingSujet(so) {
let sujetMap = [];
sujetMap = [
{ "oldvalue": "pnl-cr-1", "newvalue": "CL_FACTURE_CONSO" },
{ "oldvalue": "pnl-cr-2", "newvalue": "CL_EMM_DEM" },
{ "oldvalue": "pnl-cr-3", "newvalue": "" },
{ "oldvalue": "pnl-cr-4", "newvalue": "CL_TRAVAUX_TERRAIN" },
{ "oldvalue": "pnl-cr-8", "newvalue": "CL_DIFF_PAIEMENT" },
{ "oldvalue": "pnl-cr-10", "newvalue": "CL_SUPPORT_INTERNET" }
];
// Find option value in array to get the name of the file
//var findValue = sujetMap.filter( s => s.oldvalue == so )à
var findValue = sujetMap.filter(function(s) {return s.oldvalue === so})
if (!findValue.length) return;
return findValue[0].newvalue;
}
function secondsToMinutes(seconds) {
var minutes = Math.ceil(seconds/60);
// console.log(seconds,minutes);
return minutes;
}
function updateWaitTimeChat(time, oldValue) {
//time = 25
if( oldValue === 'pnl-cr-3') {
document.querySelector('.pnl-cr-3 .bloc-waitChat').classList.add('hidden')
} else {
if( document.querySelector('.'+ oldValue + ' .waitTimeChat') ) {
if(lang === 'fr') {
if( time > 0 && time <= 2 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'Moins de deux minutes d’attente.';
} else if( time > 2 && time < 25 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'Environ ' + parseInt(time,10) + ' minutes d’attente.';
} else if( time >= 25 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'Plus de 25 minutes d’attente.';
} else {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'Aucune attente.';
}
} else {
if( time > 0 && time <= 2 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'The wait time is less than 2 minutes.';
} else if( time > 2 && time < 25 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'The wait time is approximately ' + parseInt(time,10) + ' minutes.';
} else if( time >= 25 ) {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'The wait time is over 25 minutes.';
} else {
document.querySelector('.'+ oldValue + ' .waitTimeChat').innerHTML = 'No waiting.';
}
}
}
}
}
// affichage des blocks html avec messages pour les congés feries page nous-joindre
function afficherMessagesCongees() {
var xmlHttp;
function srvTime(){
try { //FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {//IE
console.log('Olds browsers errors :', err1);
}
xmlHttp.open('HEAD', window.location.href.toString(), false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
return xmlHttp.getResponseHeader("Date");
}
var dateServer = new Date(srvTime());
var fomatedDate = dateServer.toISOString().split('T')[0];
var serverNumericDate = dateServer.getTime()
var isHolidayDate = false;
var htmlBlockEN = null;
var htmlBlockFR = null;
fetch('/themes/nous-joindre/data/messagesCongees.json?v=' + new Date().getTime())
.then(response => {
return response.json();
})
.then(jsondata => {
var arrMsg = jsondata.holidaysMessages;
var i = 0;
var l = arrMsg.length;
for (i; i < l; i++ ) {
// string dates ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var d1 = arrMsg[i].from;
var d2 = arrMsg[i].to;
if (d1 && d2 ) {
if ( serverNumericDate >= new Date(d1).getTime() && serverNumericDate < new Date(d2).getTime()) {
isHolidayDate = true;
htmlBlockEN = arrMsg[i].messages_en;
htmlBlockFR = arrMsg[i].messages_fr;
}
}
}
var elmHtml = document.getElementById('message-ferie');
if(isHolidayDate && elmHtml) {
(document.documentElement.lang === 'fr')
? elmHtml.innerHTML = htmlBlockFR
: elmHtml.innerHTML = htmlBlockEN;
}
})
.catch(function(error) {
console.log('Fetch problem: ' + error.message);
});
}